const token=localStorage.getItem("token")

const urlParams = new URLSearchParams(window.location.search);
const courseId = urlParams.get('course_id'); // 获取 courseId 参数

const courseCardTable=document.getElementById("courseCardTable")

async function insertCourse(coursedata,url){
    const requsturl=`${config.server}`+"/api/admin/insert/course"
    var data={
        recommendMaxNum: coursedata.recommendMaxNum,
        recommendMinNum: coursedata.recommendMinNum,
        courseName:coursedata.courseName,
        courseSubject:coursedata.courseSubject,
        introduction:coursedata.introduction,
        introductionURL:url,
        isGroup:false,
        isTeam:false,
        isVIP:false,
        token:token
    }
    data.isGroup = coursedata.courseType === "group"
    data.isTeam = coursedata.courseType === "team"
    data.isVIP = coursedata.courseType === "vip"
    const response=await fetch(requsturl,{
        method:"POST",
        headers: { 'Content-Type': 'application/json' },
        body:JSON.stringify(data)
    })
    const getdata=await response.json()
    if(!response.ok){
        console.log(getdata)
        alert("插入失败")
    }else{
        alert("插入成功")
        location.reload()
    }
}
async function selectCourse(){
    const url=`${config.server}`+"/api/admin/select/all/course"
    const data={
        "token":token
    }
    const response=await fetch(url,{
        method:"POST",
        headers: { 'Content-Type': 'application/json' },
        body:JSON.stringify(data)
    })
    const getdata=await response.json()
    if(!response.ok){
        alert("查询课程失败",getdata)
        return
    }else{
        console.log(getdata)
    }
    const tableBody = document.querySelector('#coursesTable tbody');
    const courses = getdata.courses;
    tableBody.innerHTML = ''; // Clear the previous table rows


    courses.forEach(course => {
        const row = document.createElement('tr');
        var content=""
        if (course.IsGroupType){
            content="团课"
        }
        if (course.IsTeamType){
            content+="小班"
        }
        if (course.isVIP){
            content+="私教课"
        }
        row.innerHTML = `
            <td>${course.CourseId}</td>
            <td>${course.CourseName}</td>
            <td>${course.CourseSubject}</td>
            <td>${course.Introduction}</td>
            <td>${content}</td>
            <td>${course.RecommendMaxNum}</td>
            <td>${course.RecommendMinNum}</td>
        `;
        tableBody.appendChild(row);
    });

}
async function deleteCourse(courseName){
    const url=`${config.server}`+"/api/admin/delete/course/by/name"
    const data={
        "course_name":courseName,
        "token":token
    }
    const response=await fetch(url,{
        method:"POST",
        headers: { 'Content-Type': 'application/json' },
        body:JSON.stringify(data)
    })
    const getdata=await response.json()
    if(!response.ok){
        alert("删除课程失败",getdata)
    }else{
        alert("删除课程成功")
        console.log(getdata)
    }
}
function toggleAccordion(element){
    var nextElement=element.nextElementSibling
    // style 非常重要，不然就会要点击两次才能
    var style = window.getComputedStyle(nextElement);
        
    if (style.display === "none") {
        nextElement.style.display = "block";  // 显示折叠内容
    } else {
        nextElement.style.display = "none";  // 隐藏折叠内容
    }
}
function toggleAccordionSelect(element){
    var nextElement=element.nextElementSibling
    var style = window.getComputedStyle(nextElement);
    if (style.display === "none") {
        nextElement.style.display = "block";  // 显示折叠内容
        selectCourse()
    } else {
        nextElement.style.display = "none";  // 隐藏折叠内容
    }
}
var url
const insertFormInfo=document.getElementById("insertFormInfo")
//const deleteFormInfo=document.getElementById("deleteFormInfo")
insertFormInfo.addEventListener("submit",function(event){
    event.preventDefault()
    const formData = new FormData(this)
    const data = Object.fromEntries(formData.entries())
    console.log(data)
    console.log("when insert , the url is",url)
    insertCourse(data,url)
})

const submitImgButton=document.getElementById("submitImg")
submitImgButton.addEventListener("click",async function(){
    const fileInput=document.getElementById("fileInput")
    const file = fileInput.files[0]
    if (file) {
        url = await utils.uploadPicture(file);
        console.log('上传的URL:', url);
        if (url==null){
            alert("上传图片失败",url)
            return
        }else{
            alert("图片上传成功,请继续填写课程内容"+url)
        }
    } else {
        alert("请选择完成图片之后再尝试提交")
    }
})
const deleteButton=document.getElementById("deleteCourseButton")
deleteButton.addEventListener("click",function(){
    const deleteCourseName=document.getElementById("deleteCourseName")
    deleteCourse(deleteCourseName.value)
})

async function handleCourseCard(){
    if (courseId!=null){
        courseCardTable.style.display="table";
        const caption=document.createElement("caption");
        caption.textContent="courseId 为 "+courseId+"的课程信息表";
        courseCardTable.appendChild(caption);
        courseInfo=await requestSelectCourseInfoByCourseId(courseId);
        console.log(courseInfo);
        tbody=document.createElement("tbody");

        const rows = [
            ["CourseId", courseInfo.courseInfo.CourseId],
            ["CourseName", courseInfo.courseInfo.CourseName],
            ["CourseSubject", courseInfo.courseInfo.CourseSubject],
            ["CreatedAt", courseInfo.courseInfo.CreatedAt],
            ["Introduction", courseInfo.courseInfo.Introduction],
            ["IntroductionURL", courseInfo.courseInfo.IntroductionURL],
            ["IsGroupType", courseInfo.courseInfo.IsGroupType ? "是" : "否"],
            ["IsTeamType", courseInfo.courseInfo.IsTeamType ? "是" : "否"],
            ["IsVipType", courseInfo.courseInfo.IsVipType ? "是" : "否"],
            ["RecommendMaxNum", courseInfo.courseInfo.RecommendMaxNum],
            ["RecommendMinNum", courseInfo.courseInfo.RecommendMinNum],
            ["AdminId", courseInfo.courseInfo.AdminId]
        ];

        // 遍历数据并填充到表格行
        rows.forEach(([label, value]) => {
            const tr = document.createElement("tr");

            // 创建标签列
            const tdLabel = document.createElement("td");
            tdLabel.textContent = label;
            tr.appendChild(tdLabel);

            // 创建值列
            const tdValue = document.createElement("td");
            tdValue.innerHTML = value; // 允许html内容（如图片标签）
            tr.appendChild(tdValue);

            tbody.appendChild(tr);
        });
        const backBtnCell=document.createElement("td");
        const backBtn=document.createElement("button");
        backBtnCell.appendChild(backBtn);
        backBtn.innerText="返回到上一页"
        backBtn.addEventListener("click",()=>{
            window.history.back()
        })
        const tr=document.createElement("tr");
        tr.appendChild(backBtnCell);
        courseCardTable.appendChild(tr)

        // 将 tbody 添加到表格中
        courseCardTable.appendChild(tbody);
    }
}
async function requestSelectCourseInfoByCourseId(courseId){
    const url=`${config.server}`+"/api/select/course"
    const data={
        course_id:parseInt(courseId)
    }
    const response=await fetch(url,{
        method:"POST",
        headers: { 'Content-Type': 'application/json' },
        body:JSON.stringify(data)
    })
    const getdata=await response.json()
    if(response.ok){
        return getdata
    }else{
        console.log("获取数据失败",getdata)
    }
}

handleCourseCard()